<template>
  <div class="tag-input-item-container">
    <el-form :model="form" ref="ruleFormRef" :rules="rules" style="flex:1;padding-top:5px">
      <el-form-item
        v-for="handlerItem in TagInputItemData"
        style="margin-bottom: 15px;"
        :key="handlerItem.key"
        :label="handlerItem.label"
        :label-width="90"
        :prop="handlerItem.key"
        :required="handlerItem.require">
        <el-input v-model="form[handlerItem.key]" :type="handlerItem.type" @blur="submitForm(ruleFormRef, handlerItem.key)">
          <template v-if="handlerItem.key === 'bidfloor'" #append>元</template>
        </el-input>
      </el-form-item>
    </el-form>
    <div class="right-box">
      <el-popconfirm
        confirm-button-text="确定"
        cancel-button-text="取消"
        :icon="InfoFilled"
        icon-color="#626AEF"
        title="您确定删除该选项吗?"
        @confirm="deleteItem"
      >
        <template #reference>
          <el-icon size="30" color="#e4393c" style="cursor: pointer;"><Delete /></el-icon>
        </template>
      </el-popconfirm>
    </div>
  </div>
</template>

<script setup lang="ts">
import { InfoFilled } from '@element-plus/icons-vue'
import { defineProps, ref, reactive } from 'vue';
import { TagInputItemData, HANDLE_TYPE_ENUM, TagInputItemOriginData } from '@/types/home/constData.ts'
import type { ITagInputItemData } from '@/types/home/type'
import type { FormRules, FormInstance } from 'element-plus'
import { watch } from 'vue';

const emit = defineEmits<{
  (event: 'onTagInputItemComplete', type: string, data: ITagInputItemData | undefined): void
}>()
const props = defineProps<{
  itemData: ITagInputItemData,
}>();
const ruleFormRef = ref();
let form = ref<ITagInputItemData>(TagInputItemOriginData)
const rules = reactive<FormRules<ITagInputItemData>>({
  tagid: [
    { required: true, message: '请输入广告位ID', trigger: 'blur' }
  ],
  keyword: [
    { required: true, message: '请输入关键词', trigger: 'blur' }
  ],
  bidfloor: [
    { required: true, message: '请输入竞价', trigger: 'blur' }
  ]
})
watch(props.itemData, (newVal) => {
  setTimeout(() => {
    ruleFormRef.value.resetFields({...newVal})
    form.value = {...newVal}
  }, 0)
}, {
  immediate: true
})
const submitForm = async (formEl: FormInstance | undefined, modifyKey: string) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (props.itemData[modifyKey] !== form.value[modifyKey]) {
        emit('onTagInputItemComplete', HANDLE_TYPE_ENUM.TYPE_UPDATE, {...form.value})
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
const deleteItem = () => {
  emit('onTagInputItemComplete', HANDLE_TYPE_ENUM.TYPE_DELETE, undefined)
}
</script>

<style scoped lang="scss">
.tag-input-item-container{
  display: flex;
  align-items: center;
  .right-box{
    width: 60px;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>